<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
            <el-form-item label="有效开始日期" prop="validStartDate">
                <el-date-picker clearable v-model="queryParams.validStartDate" type="date" value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd" placeholder="请选择有效开始日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="有效结束日期" prop="validEndDate">
                <el-date-picker clearable v-model="queryParams.validEndDate" type="date" value-format="yyyy-MM-dd"
                    format="yyyy-MM-dd" placeholder="请选择有效结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="生成标志" prop="generateEnabled">
                <el-select v-model="queryParams.generateEnabled">
                    <el-option v-for="item in generateEnabledList" :key="item.id" :value="item.id" :label="item.name">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['film:cardOrderDetail:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['film:cardOrderDetail:remove']">删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="cardOrderDetailList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" type="index" width="55" />
            <el-table-column label="卡券类型编号" align="center" prop="cardTypeId" :formatter="typeFormatter" min-width="150"
                :show-overflow-tooltip="true" />
            <!-- <el-table-column label="单价" align="center" prop="unitPrice" min-width="100" :show-overflow-tooltip="true" /> -->
            <el-table-column label="生成数量" align="center" prop="quantity" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="积分额度" align="center" prop="integralLimit" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="次数额度" align="center" prop="maxRedeemTimes" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="抵扣额度" align="center" prop="quotaLimit" min-width="100"
                :show-overflow-tooltip="true" />
            <el-table-column label="有效开始日期" align="center" prop="validStartDate" width="120">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.validStartDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="有效结束日期" align="center" prop="validEndDate" width="120">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.validEndDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="订单金额 " align="center" prop="amount" min-width="100" :show-overflow-tooltip="true" /> -->
            <el-table-column label="起始卡号" align="center" prop="startCardNo" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="结束卡号" align="center" prop="endCardNo" min-width="200"
                :show-overflow-tooltip="true" />
            <el-table-column label="生成标志" align="center" prop="generateEnabled" min-width="100"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                    <div v-if="scope.row.generateEnabled == 0">未生成</div>
                    <div v-if="scope.row.generateEnabled == 1">已生成</div>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="260">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" @click="handleCreated(scope.row)"
                        v-if="scope.row.generateEnabled == 0"
                        v-hasPermi="['film:cardOrderDetail:created']">生成卡券</el-button>
                    <el-button size="mini" type="text" @click="handleCard(scope.row)"
                        v-hasPermi="['film:cardOrderDetail:card']">卡券列表</el-button>
                    <el-button size="mini" type="text" @click="handleTimes(scope.row)"
                        v-hasPermi="['film:cardOrderDetail:times']">延期时间</el-button>
                    <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
                        v-hasPermi="['film:cardOrderDetail:edit']">修改</el-button>
                    <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                        v-hasPermi="['film:cardOrderDetail:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改企业卡券订单明细对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form class="addData" :inline="true" ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="卡券类型" prop="cardTypeId">
                            <el-select v-model="form.cardTypeId" @change="selectCardTypes">
                                <el-option v-for="item in cardTypeList" :key="item.id" :value="item.id"
                                    :label="item.typeCode"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="生成数量" prop="quantity">
                            <el-input-number :controls="false" v-model="form.quantity" :step="1" step-strictly
                                placeholder="请输入生成数量" :min="1"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="12">
                        <el-form-item label="单价" prop="unitPrice">
                            <el-input-number v-model="form.unitPrice" :precision="2" :step="0.1" :max="1000" :min="1"
                                @change="calculateAmount" :controls="false" placeholder="请输入单价"></el-input-number>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <!-- <el-row> -->

                <!-- <el-col :span="12">
                        <el-form-item label="订单金额 " prop="amount">
                            <el-input-number v-model="form.amount" :precision="2" :step="0.1" :max="1000000000000000000000" :min="1"
                                disabled :controls="false" placeholder="请输入订单金额"></el-input-number>
                        </el-form-item>
                    </el-col> -->
                <!-- </el-row> -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开始日期" prop="validStartDate">
                            <el-date-picker clearable v-model="form.validStartDate" type="date"
                                value-format="yyyy-MM-dd" placeholder="请选择有效开始日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="结束日期" prop="validEndDate">
                            <el-date-picker clearable v-model="form.validEndDate" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择有效结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row>
                    <el-col :span="12">
                        <el-form-item label="起始卡号" prop="startCardNo">
                            <el-input v-model="form.startCardNo" placeholder="请输入起始卡号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结束卡号" prop="endCardNo">
                            <el-input v-model="form.endCardNo" placeholder="请输入结束卡号" />
                        </el-form-item>
                    </el-col>
                </el-row> -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input class="longData" v-model="form.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <el-dialog title="卡券列表" :visible.sync="Cardopen" width="1000px" append-to-body>
            <div
                style="display: flex;align-items: center;justify-content: space-between;padding-right: 20px;padding-bottom: 20px;">
                <div></div>
                <div> <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                        v-hasPermi="['film:cardOrderDetail:export']">导出</el-button></div>
            </div>
            <el-table :data="tCardList" ref="tCard">
                <el-table-column label="序号" align="center" type="index" width="55" />
                <el-table-column label="卡号" align="center" prop="cardNo" min-width="200" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="卡密" align="center" prop="cardPwd" min-width="150" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="卡券类型编号" align="center" prop="cardTypeId" min-width="150"
                    :show-overflow-tooltip="true" :formatter="typeFormatter">
                </el-table-column>
                <el-table-column label="计量方式" align="center" prop="cardMode" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.cardMode == 1">观影次数卡</div>
                        <div v-if="scope.row.cardMode == 2">积分卡</div>
                    </template>
                </el-table-column>
                <el-table-column label="原始金额或次数" align="center" prop="faceValue" min-width="150"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="剩余金额或次数" align="center" prop="balance" min-width="150"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="卡券状态" align="center" prop="status" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.status == 0">初始</div>
                        <div v-if="scope.row.status == 1">已激活</div>
                        <div v-if="scope.row.status == 2">已用完</div>
                        <div v-if="scope.row.status == 3">已过期</div>
                        <div v-if="scope.row.status == 4">锁定</div>
                    </template>
                </el-table-column>
                <el-table-column label="是否激活" align="center" prop="isBound" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.isBound == 0">未绑定</div>
                        <div v-if="scope.row.isBound == 1">已绑定</div>
                    </template>
                </el-table-column>
                <el-table-column label="是否已完全消费" align="center" prop="isConsumed" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.isBound == 0">未完全消费</div>
                        <div v-if="scope.row.isBound == 1">已完全消费</div>
                        <!-- <el-input v-model="scope.row.isConsumed" placeholder="请输入是否已完全消费" /> -->
                    </template>
                </el-table-column>
                <el-table-column label="激活人ID" align="center" prop="userId" min-width="150"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="用户账号" align="center" prop="userName" min-width="150"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="手机号码" align="center" prop="phonenumber" min-width="150"
                    :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="激活时间" align="center" prop="activatedTime" min-width="150"
                    :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">
                        <el-date-picker clearable v-model="scope.row.activatedTime" type="date"
                            value-format="yyyy-MM-dd" placeholder="请选择激活时间" />
                    </template> -->
                </el-table-column>
                <el-table-column label="最后使用时间" align="center" prop="usedTime" min-width="150"
                    :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">
                        <el-date-picker clearable v-model="scope.row.usedTime" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择最后使用时间" />
                    </template> -->
                </el-table-column>
                <el-table-column label="有效开始日期" align="center" prop="validStartDate" min-width="150"
                    :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">
                        <el-date-picker clearable v-model="scope.row.validStartDate" type="date"
                            value-format="yyyy-MM-dd" placeholder="请选择有效开始日期" />
                    </template> -->
                </el-table-column>
                <el-table-column label="有效结束日期" align="center" prop="validEndDate" min-width="150"
                    :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">
                        <el-date-picker clearable v-model="scope.row.validEndDate" type="date" value-format="yyyy-MM-dd"
                            placeholder="请选择有效结束日期" />
                    </template> -->
                </el-table-column>
                <el-table-column label="是否能兑换电影" align="center" prop="movieEnabled" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.movieEnabled == 0">能</div>
                        <div v-if="scope.row.movieEnabled == 1">不能</div>
                        <!-- <el-input v-model="scope.row.movieEnabled" placeholder="请输入是否能兑换电影启用，0=能，1=不能" /> -->
                    </template>
                </el-table-column>
                <el-table-column label="是否能兑换福利" align="center" prop="welfareEnabled" min-width="150"
                    :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <div v-if="scope.row.welfareEnabled == 0">能</div>
                        <div v-if="scope.row.welfareEnabled == 1">不能</div>
                        <!-- <el-input v-model="scope.row.welfareEnabled" placeholder="请输入是否能兑换福利，0=能，1=不能" /> -->
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="cardTotal > 0" :total="cardTotal" :page.sync="cardParams.pageNum"
                :limit.sync="cardParams.pageSize" @pagination="getCardList" />
        </el-dialog>


        <el-dialog title="延期时间" :visible.sync="Timesopen" width="800px" append-to-body>
            <el-form :inline="true" ref="formTime" :model="formTime" :rules="rules" label-width="80px">

                <el-form-item label="开始日期" prop="validStartDate">
                    <el-date-picker clearable v-model="formTime.validStartDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择有效开始日期">
                    </el-date-picker>
                </el-form-item>


                <el-form-item label="结束日期" prop="validEndDate">
                    <el-date-picker clearable v-model="formTime.validEndDate" type="date" value-format="yyyy-MM-dd"
                        placeholder="请选择有效结束日期">
                    </el-date-picker>
                </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFormTime">确 定</el-button>
                <el-button @click="Timesopen = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { listCards, generate, listCardOrderDetail, getCardOrderDetail, delCardOrderDetail, addCardOrderDetail, updateCardOrderDetail, postpone } from "@/api/company/cardOrderDetail";
import { listselectType } from "@/api/cardType/cardType";
export default {
    name: "CardOrderDetail",
    data() {
        return {
            formTime: {},
            Timesopen: false,
            cardParams: {
                pageNum: 1,
                pageSize: 10,
            },
            cardTotal: 0,
            orderDetailId: "",
            tCardList: [],
            Cardopen: false,
            cardTypeList: [],
            generateEnabledList: [
                {
                    id: 0,
                    name: '未生成'
                },
                {
                    id: 1,
                    name: '已生成'
                }
            ],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedTCard: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 企业卡券订单明细表格数据
            cardOrderDetailList: [],
            // 卡券信息表格数据
            tCardList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderId: null,
                cardTypeId: null,
                unitPrice: null,
                quantity: null,
                integralLimit: null,
                maxRedeemTimes: null,
                quotaLimit: null,
                validStartDate: null,
                validEndDate: null,
                amount: null,
                startCardNo: null,
                endCardNo: null,
                generateEnabled: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                cardTypeId: [
                    { required: true, message: "关联卡券类型不能为空", trigger: "blur" }
                ],
                unitPrice: [
                    { required: true, message: "单价不能为空", trigger: "blur" }
                ],
                quantity: [
                    { required: true, message: "生成数量不能为空", trigger: "blur" }
                ],
                amount: [
                    { required: true, message: "订单金额不能为空", trigger: "blur" }
                ],
                validStartDate: [
                    { required: true, message: "开始日期不能为空", trigger: "blur" }
                ],
                validEndDate: [
                    { required: true, message: "结束日期不能为空", trigger: "blur" }
                ]
            }
        };
    },
    async created() {
        await listselectType().then(res => {
            this.cardTypeList = res.rows;
        })
        this.getList();
    },
    methods: {
        submitFormTime() {
            postpone(this.formTime).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.Timesopen = false
                this.getList();
            })
        },
        handleTimes(row) {
            this.reset();
            getCardOrderDetail(row.id).then(response => {
                this.formTime = response.data;
                this.Timesopen = true;
            });
        },
        calculateAmount() {
            if (this.form.unitPrice && this.form.quantity) {
                this.form.amount = this.form.unitPrice * this.form.quantity;
            } else {
                this.form.amount = 0;  // 如果单价或数量为空，金额设为 0
            }
        },
        typeFormatter(row) {
            let data = this.cardTypeList.find(item => row.cardTypeId == item.id)
            return data.typeCode
        },
        selectCardTypes(e) {
            this.form.integralLimit = this.cardTypeList.find(item => e == item.id).integralLimit
            this.form.quotaLimit = this.cardTypeList.find(item => e == item.id).quotaLimit
            this.form.maxRedeemTimes = this.cardTypeList.find(item => e == item.id).maxRedeemTimes
        },
        /** 查询企业卡券订单明细列表 */
        getList() {
            this.loading = true;
            this.queryParams.orderId = this.$route.query.orderId
            listCardOrderDetail(this.queryParams).then(response => {
                this.cardOrderDetailList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                orderId: null,
                cardTypeId: null,
                unitPrice: null,
                quantity: null,
                integralLimit: null,
                maxRedeemTimes: null,
                quotaLimit: null,
                validStartDate: null,
                validEndDate: null,
                amount: null,
                startCardNo: null,
                endCardNo: null,
                generateEnabled: null,
                delFlag: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加企业卡券订单明细";
        },
        handleCard(row) {
            // this.cardParams.orderDetailId = row.id
            // this.getCardList()
            // this.Cardopen = true


            this.$router.push({
                path: '/orderCoupon/index',
                query: {
                    orderDetailId: row.id
                }
            })

        },
        getCardList() {
            listCards(this.cardParams).then(res => {
                this.tCardList = res.rows
                this.cardTotal = res.total
            })
        },
        handleCreated(row) {
            let cardMode = this.cardTypeList.find(item => row.cardTypeId == item.id).cardMode
            console.log(cardMode)
            this.$modal.confirm('是否确认生成卡券？').then(function () {
                return generate({
                    cardMode,
                    amount: row.amount,
                    cardTypeId: row.cardTypeId,
                    endCardNo: row.endCardNo,
                    generateEnabled: 1,
                    integralLimit: row.integralLimit,
                    maxRedeemTimes: row.maxRedeemTimes,
                    orderId: row.orderId,
                    quantity: row.quantity,
                    quotaLimit: row.quotaLimit,
                    remark: row.remark,
                    startCardNo: row.startCardNo,
                    unitPrice: row.unitPrice,
                    validEndDate: row.validEndDate,
                    validStartDate: row.validStartDate,
                    id: row.id
                });
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("操作成功");
            }).catch(() => { });
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getCardOrderDetail(id).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改企业卡券订单明细";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.form.orderId = this.$route.query.orderId
                    if (this.form.id != null) {
                        updateCardOrderDetail(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addCardOrderDetail(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除企业卡券订单明细数据项？').then(function () {
                return delCardOrderDetail(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 卡券信息序号 */
        rowTCardIndex({ row, rowIndex }) {
            row.index = rowIndex + 1;
        },
        /** 卡券信息添加按钮操作 */
        handleAddTCard() {
            let obj = {};
            obj.cardNo = "";
            obj.cardPwd = "";
            obj.cardTypeId = "";
            obj.cardMode = "";
            obj.faceValue = "";
            obj.balance = "";
            obj.status = "";
            obj.isBound = "";
            obj.isConsumed = "";
            obj.userId = "";
            obj.userName = "";
            obj.phonenumber = "";
            obj.activatedTime = "";
            obj.usedTime = "";
            obj.validStartDate = "";
            obj.validEndDate = "";
            obj.movieEnabled = "";
            obj.welfareEnabled = "";
            obj.description = "";
            obj.remark = "";
            this.tCardList.push(obj);
        },
        /** 卡券信息删除按钮操作 */
        handleDeleteTCard() {
            if (this.checkedTCard.length == 0) {
                this.$modal.msgError("请先选择要删除的卡券信息数据");
            } else {
                const tCardList = this.tCardList;
                const checkedTCard = this.checkedTCard;
                this.tCardList = tCardList.filter(function (item) {
                    return checkedTCard.indexOf(item.index) == -1
                });
            }
        },
        /** 复选框选中数据 */
        handleTCardSelectionChange(selection) {
            this.checkedTCard = selection.map(item => item.index)
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('/film/card/export', { orderDetailId: this.cardParams.orderDetailId }, `卡券列表_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>
